package com.rear.controller;

import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.util.ObjectUtils;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import com.rear.entity.SysUserEntity;
import com.rear.service.SysUserService;
import com.rear.utils.R;
import com.rear.utils.ShiroUtils;

/**
 * 登录相关
 * 
 * @author October
 * @author chenzeming@9an-data.com
 * @date 2016年11月10日 下午1:15:31
 */
@Controller
public class SysLoginController {
	@Autowired
	private Producer producer;
	
	@Autowired
	private SysUserService sysUserService;
	
	private final static Logger logger = Logger.getLogger(SysLoginController.class);
	@RequestMapping("captcha.jpg")
	public void captcha(HttpServletResponse response)throws ServletException, IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");

        //生成文字验证码
        String text = producer.createText();
        //生成图片验证码
        BufferedImage image = producer.createImage(text);
        //保存到shiro session
        ShiroUtils.setSessionAttribute(Constants.KAPTCHA_SESSION_KEY, text);
        
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
	}
	
	/**
	 * 登录
	 */
	@ResponseBody
	@RequestMapping(value = "/sys/login", method = RequestMethod.POST)
	public R login(String username, String password, String captcha)throws IOException {
		String kaptcha = ShiroUtils.getKaptcha(Constants.KAPTCHA_SESSION_KEY);
		if(!captcha.equalsIgnoreCase(kaptcha)){
			return R.error("验证码不正确");
		}
		
		try{
			Subject subject = ShiroUtils.getSubject();
			//sha256加密
			password = new Sha256Hash(password).toHex();
			UsernamePasswordToken token = new UsernamePasswordToken(username, password);
			ShiroUtils.setSessionAttribute("username", username);
			subject.login(token);
		}catch (UnknownAccountException e) {
			return R.error(e.getMessage());
		}catch (IncorrectCredentialsException e) {
			return R.error(e.getMessage());
		}catch (LockedAccountException e) {
			return R.error(e.getMessage());
		}catch (AuthenticationException e) {
			return R.error("账户验证失败");
		}
	    
		return R.ok();
	}
	
	/**
	 * 退出
	 */
	@RequestMapping(value = "logout", method = RequestMethod.GET)
	public String logout() {
		ShiroUtils.logout();
		return "redirect:login.html";
	}
	
	/**
	 * 登录
	 */
	@ResponseBody
	@RequestMapping(value = "/sys/login/qq", method = RequestMethod.GET)
	public R loginQQ(String access_token, String openid)throws IOException {
		
		try{
			
			logger.info("access_token:"+access_token);
			logger.info("openid:"+openid);

			Subject subject = ShiroUtils.getSubject();
			SysUserEntity sysUserEntity=sysUserService.getQQopenid(openid);
			UsernamePasswordToken token ;
			logger.info(ObjectUtils.isEmpty(sysUserEntity));
			if(ObjectUtils.isEmpty(sysUserEntity)){
				token = new UsernamePasswordToken("1", "1");
				return R.error("请先绑定信息后再登录");
			}else{
				token = new UsernamePasswordToken(sysUserEntity.getUsername(), sysUserEntity.getPassword());
				ShiroUtils.setSessionAttribute("username", sysUserEntity.getUsername());
				subject.login(token);
			}
		}catch (UnknownAccountException e) {
			return R.error(e.getMessage());
		}catch (IncorrectCredentialsException e) {
			return R.error(e.getMessage());
		}catch (LockedAccountException e) {
			return R.error(e.getMessage());
		}catch (AuthenticationException e) {
			return R.error("账户验证失败");
		}
	    
		return R.ok();
	}
	
	/**
	 * 绑定QQ
	 */
	@ResponseBody
	@RequestMapping(value = "/sys/login/bind/qq", method = RequestMethod.GET)
	public R bindQQ(String openid,
			HttpServletRequest req,
			HttpServletResponse resp)throws IOException {
		try{
			String username =req.getSession().getAttribute("username").toString();
			logger.info("username:"+username);
			logger.info("openid:"+openid);
			SysUserEntity sysUserEntity=sysUserService.getQQopenid(openid);
			if(ObjectUtils.isEmpty(sysUserEntity)){
				int a=sysUserService.bindQQ(openid, username);
				if(a==0){
					return R.error("绑定失败");
				}
			}else{
				return R.error("改QQ号码已经绑定其他账号");
			}
		}catch (UnknownAccountException e) {
			return R.error(e.getMessage());
		}catch (IncorrectCredentialsException e) {
			return R.error(e.getMessage());
		}catch (LockedAccountException e) {
			return R.error(e.getMessage());
		}catch (AuthenticationException e) {
			return R.error("账户验证失败");
		}
	    
		return R.ok();
	}
	
}
